<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.com_name" placeholder="搜索" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        {{ $t('table.add') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      >
      </el-table-column>
      <!--<el-table-column label="全选"  align="center" width="80" >-->
      <!--<el-checkbox :indeterminate="isIndeterminate" v-model="check" @change="handleCheckAllChange"></el-checkbox>-->

      <!--</el-table-column>-->
      <el-table-column label="网站名称"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="网站标签"  align="center">
         <template slot-scope="{row}">
          <span>{{ row.tag }}</span>
        </template>
      </el-table-column>
      <el-table-column label="网站域名"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.urlhost }}</span>
        </template>
      </el-table-column>
      <el-table-column label="网站路径"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.urlpath }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.is_enabled ? '是' :'否'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140px" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="showDetail(row)">
            详情
          </el-button>
            <el-button type="success" size="mini" @click="editDetail(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row.id,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-dialog v-dialogDrag :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px"
               style="width: 400px; margin-left:50px;"
      >
        <!-- <input type="hidden" v-model="temp.id"> -->
        <el-form-item label="网站名称" prop="com_name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="网站标签" prop="address">
          <el-input v-model="temp.tag"/>
        </el-form-item>
        <el-form-item label="网站域名" prop="address">
          <el-input v-model="temp.urlhost"/>
        </el-form-item>
          <el-form-item label="网站路径" prop="address">
          <el-input v-model="temp.urlpath"/>
        </el-form-item>
        <el-form-item label="是否启用" prop="address">
          <el-switch v-model="temp.isEnabled"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="请选择需要同步的账号">
      <el-tree
        :props="tree"
        :load="loadNode"
        lazy
        show-checkbox
        node-key="id"
        ref="tree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSync">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogGroupSMSNotice" title="请输入短信内容">
      <el-form ref="dataForm"  :model="GroupSMSNoticeData" label-position="left"
               label-width="90px"
               style="width: 420px; margin-left:50px;"
      >
        <el-form-item label="通知类型">
          <el-radio-group v-model="GroupSMSNoticeData.type">
            <el-radio label="已经开始">开始通知</el-radio>
            <el-radio label="即将结束">结束通知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="证书名称">
          <el-input v-model="GroupSMSNoticeData.name"></el-input>
        </el-form-item>
        <el-form-item label="短信内容" prop="message">
          <el-input type="textarea"
                    :rows="5"
                    maxlength="60"
                   
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="GroupSMSNotice" v-loading.fullscreen.lock="fullscreenLoading"
        >{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogBless" title="请输入短信内容">
      <el-form ref="dataForm" :rules="rules" :model="BlessData" label-position="left" label-width="90px"
               style="width: 420px; margin-left:50px;"
      >
        <el-form-item label="通知类型">
          <el-radio-group v-model="BlessData.type">
            <el-radio label="1">节日模板1</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="节日名称">
          <el-input v-model="BlessData.name"></el-input>
        </el-form-item>

        <el-form-item label="短信内容" prop="message">
         
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="BlessSubmit" v-loading.fullscreen.lock="fullscreenLoading"
        >{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="sendResultDialog" title="发送结果">
      <span>发送成功{{ sendResult.success_num }}条，发送失败{{ sendResult.error_num }}条</span>
      <el-table
        :data="sendResult.success"
        stripe
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="客户信息"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="msg"
          label="发送状态"
        >
        </el-table-column>
      </el-table>
      <div style="height: 20px"></div>
      <span>发送失败列表</span>
      <el-table
        :data="sendResult.error"
        stripe
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="客户信息"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="msg"
          label="发送状态"
        >
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="sendResultDialog = false">{{ $t('table.confirm') }}</el-button>
            </span>
    </el-dialog>


        <el-dialog v-dialogDrag title="版本详情" :visible.sync="showDetailVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px"
               style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="网站名称" prop="version">
          <!-- <el-input v-model="temp.name" :disabled="true"></el-input> -->
          <span>{{ temp.name }}</span>
        </el-form-item>
        <el-form-item label="网站标签" prop="info">
          <!-- <el-input v-model="temp.tag" :disabled="true"></el-input> -->
           <span>{{ temp.tag }}</span>
        </el-form-item>
        <el-form-item label="网站域名" prop="info">
          <!-- <el-input v-model="temp.urlhost" :disabled="true"/> -->
          <span>{{ temp.urlhost }}</span>
        </el-form-item>
        <el-form-item label="网站路径" prop="info">
          <!-- <el-input v-model="temp.urlpath" :disabled="true"/> -->
          <span>{{ temp.urlpath }}</span>
        </el-form-item>
         <el-form-item label="创建时间" prop="info">
          <!-- <el-input v-model="temp.create_time" :disabled="true"/> -->
          <span>{{ temp.create_time }}</span>
        </el-form-item>
        <el-form-item label="变更时间" prop="info">
          <!-- <el-input v-model="temp.update_time" :disabled="true"/> -->
           <span>{{ temp.update_time }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        
      </div>
    </el-dialog>

     <el-dialog v-dialogDrag title="版本详情" :visible.sync="editDetailVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px"
               style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="网站名称" prop="version">
          <el-input v-model="temp.name" ></el-input>
        </el-form-item>
        <el-form-item label="网站标签" prop="info">
          <el-input v-model="temp.tag" ></el-input>
        </el-form-item>
        <el-form-item label="网站域名" prop="info">
          <el-input v-model="temp.urlhost" />
        </el-form-item>
        <el-form-item label="网站路径" prop="info">
          <el-input v-model="temp.urlpath"/>
        </el-form-item>
         <!-- <el-form-item label="创建时间" prop="info">
          <el-input v-model="temp.create_time" />
        </el-form-item>
        <el-form-item label="变更时间" prop="info">
          <el-input v-model="temp.update_time" />
        </el-form-item> -->
      </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="editDetailVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData(temp.id)">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style>
.my-autocomplete li {
  line-height: normal;
  padding: 7px;
}

.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
  color: #ddd;
}
</style>
<script>
import {
  fetchList,
  delCustomer,
  createcustomer,
  updatecustomer,
  delManger,
  getAllTags,
  getAllRemarks,
  customerSync
} from '@/api/customer'
import { getTree, getLeaf, getAllInfo } from '@/api/user'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { GroupSMSNotice, GroupSMSBless } from '@/api/GroupSMS'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      editDetailVisible:false,// 编辑面板
      showDetailVisible:false,// 详情展示面板
      restaurants: [], // 全局搜索手机号姓名  存储
      BlessData: {
        type: '1',
        name: ''
      },//  短信新群发
      fullscreenLoading: false,
      dialogBless: false,
      GroupSMSNoticeData: {
        name: '',
        type: '已经开始'
      },
      dialogGroupSMSNotice: false,
      sync: {},
      tree: {
        label: 'real_name',
        children: 'zones',
        isLeaf: 'leaf'
      },
      tags: [], // 搜索中的标签
      remarks: [], // 搜索中的备注
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        telephone: '',
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '-id',
        tag: '',
        remarks: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID 正序', key: '+id' }, { label: 'ID 倒序', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],

      temp: {
        id: undefined,
        com_name: '',
        manager: [],
        address: '',
        url: '',
        remarks: '',
        tags: [],
        isEnabled:true
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '网站名称必须填写', trigger: 'change' }],
        manager: [{ required: true, message: '负责人必须填写', trigger: 'change' }]
      },
      downloadLoading: false,
      multipleSelection: [],
      sendResult: {
        success: [],
        error: [],
        error_num: 0,
        success_num: 0
      },
      sendResultDialog: false
    }
  },
  created() {
    this.getList()
    // 
    // this.getAllRemarks()
    this.restaurants = this.loadAll()
  },
  methods: {
    editDetail(row){
      this.resetTemp()
      this.temp = Object.assign({}, row)
      // this.dialogStatus = 'create'
      this.editDetailVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    showDetail(row){
       this.resetTemp()
      this.temp = Object.assign({}, row)
      this.showDetailVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    jump_newPage(id) {
      this.$router.push({ path: '/certificate/index/' + id })
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      //调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll() {
      getAllInfo().then(response => {
        console.log(response.data)
        this.restaurants = response.data
      })
    },
    handleSelect(item, index) {
      this.temp.manager.splice(index, 1)
      this.temp.manager.push({ 'name': item['value'], 'telphone': item['address'] })
    },
    handleIconClick(ev) {
      console.log(ev)
    },

    BlessSubmit() {
      if (this.BlessData.name == '') {
        this.$message({
          message: '请填入节日名称',
          type: 'error'
        })
        return false
      }
      this.fullscreenLoading = true
      this.BlessData.PhoneNums = this.multipleSelection
      GroupSMSBless(this.BlessData).then(response => {
        this.sendResult = response.data
        this.dialogBless = false
        this.sendResultDialog = true
        this.fullscreenLoading = false
      })
    },
    GroupSMSNotice() {
      if (this.GroupSMSNoticeData.name == '') {
        this.$message({
          message: '请填入证书名称',
          type: 'error'
        })
        return false
      }
      this.fullscreenLoading = true
      this.GroupSMSNoticeData.PhoneNums = this.multipleSelection
      GroupSMSNotice(this.GroupSMSNoticeData).then(response => {
        this.sendResult = response.data
        this.dialogGroupSMSNotice = false
        this.sendResultDialog = true
        this.fullscreenLoading = false
      })
    },
    saveSync() {
      if (this.$refs.tree.getCheckedKeys().length == 0) {
        this.$message({
          message: '请先选择账号',
          type: 'error'
        })
        return false
      }
      this.sync.receive_ids = this.$refs.tree.getCheckedKeys()
      this.sync.data_ids = this.multipleSelection
      customerSync(this.sync).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.dialogPvVisible = false
      })

    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        getTree().then(response => {
          return resolve(response.data)
        })
      } else {
        getLeaf(node.data.id).then(response => {
          return resolve(response.data)
        })
      }
    },
    GroupSMSDialog() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '请您先选择数据',
          type: 'error'
        })
        return false
      }
      this.dialogGroupSMSNotice = true
    },
    GroupBlessDialog() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '请您先选择数据',
          type: 'error'
        })
        return false
      }
      this.dialogBless = true
    },
    dataSync() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '请您先选择数据',
          type: 'error'
        })
        return false
      }
      this.dialogPvVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getAllTags() {
      getAllTags().then(response => {
        this.tags = response.data
      })
    },
    getAllRemarks() {
      getAllRemarks().then(response => {
        this.remarks = response.data
      })
    },
    removeManager(listID, index) {
      if (this.dialogStatus == 'update') {
        for (var i = 0; i < this.list.length; i++) {
          if (this.list[i].id == listID) {
            if (this.list[i].manager[index].id != 0) {
              delManger(this.list[i].manager[index].id).then(response => {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
              })
            }
            this.list[i].manager.splice(index, 1)
            return false
          }
        }
      } else {
        this.temp.manager.splice(index, 1)
      }

    },
    addManager(customer_id) {
      if (this.dialogStatus == 'update') {
        for (var i = 0; i < this.list.length; i++) {
          if (customer_id == this.list[i].id) {
            this.list[i].manager.push({
              'id': 0
            })
            // extend(this.list[i].manager,{});
            return false
          }
        }
      } else {
        this.temp.manager.push({
          'id': 0
        })
      }
    },
    getList() {
      this.listLoading = false
      this.listLoading = true
      this.list = []
      

      // Just to simulate the time of the request
      setTimeout(() => {
        this.listLoading = false
      }, 1.5 * 1000)
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
      
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        com_name: '',
        manager: [{
          'id': 0
        }],
        address: '',
        url: '',
        remarks: '',
        tags: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          createcustomer(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
            // 
          })
        }
      })

    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      if (row.tags) {
        this.temp.tags = []
        for (var i = 0; i < row.tags.length; i++) {
          this.temp.tags.push(row.tags[i].tag)
        }
      }

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData(id) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updatecustomer(id,tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.editDetailVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
            // 
          })
        }
      })

    },
    handleDelete(customer_id, index) {
      this.$confirm('您确定要删除吗?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delCustomer(customer_id).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        })

    },
    handleDownload() {
      this.downloadLoading = true

      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['公司名称', '公司地址', '备注', '负责人信息']
        const filterVal = ['com_name', 'address', 'remarks', 'customer']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
